<template>
  <div class="container">
    <div class="upper-area">
      <div class="upload-area">
        <div class="upload-file">
          <el-upload
              ref="leftUpload"
              action="/api/model/uploadImage?sign=left"
              :limit="1"
              :show-file-list="false"
              :on-exceed="handleExceed"
              :on-progress="handleProgress"
              :on-success="handleSuccess"
              :on-error="handleError"
              accept=".jpg,.jpeg,.png">
            <div class="img-preview">
              <img src="../assets/image/image_background.png" alt="" class="image-background"/>
              <div class="inner-image-box">
                <img :src="leftBase64" alt=""
                     style="width: 90%;height: 90%;border-radius: 5px"/>
              </div>
            </div>
          </el-upload>
        </div>
        <div class="middle-blank"></div>
        <div class="upload-file">
          <el-upload
              ref="rightUpload"
              action="/api/model/uploadImage?sign=right"
              :show-file-list="false"
              :limit="1"
              :on-exceed="handleExceed"
              :on-progress="handleProgress"
              :on-success="handleSuccess"
              :on-error="handleError"
              accept=".jpg,.jpeg,.png">
            <div class="img-preview">
              <img src="../assets/image/image_background.png" alt="" class="image-background"/>
              <div class="inner-image-box">
                <img :src="rightBase64" alt=""
                     style="width: 90%;height: 90%;border-radius: 5px"/>
              </div>
            </div>
          </el-upload>
        </div>
      </div>
      <el-button class="start-btn" @click="startDiagnosis">开始识别</el-button>
    </div>
    <div class="result-area"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import {enhanceImage, getProbList} from "@/api/diagnosis";
import axios from "axios";

const animationDuration = 2000
export default {
  name: 'InternalPage',
  data() {
    return {
      loading: null,
      leftBase64: 'https://fundusdetection.oss-cn-beijing.aliyuncs.com/7_left.jpg',
      rightBase64: 'https://fundusdetection.oss-cn-beijing.aliyuncs.com/7_right.jpg',
      form: {
        leftFilename: '',
        rightFilename: '',
        description: '',
      },
      // 柱状图y轴数值
      probData: [0, 1, 0, 0, 0, 1, 0, 0],
      // 柱状图轴内容
      diseaseBarDataX: ['N', 'D', 'G', 'C', 'A', 'H', 'M', 'O'],
    }
  },
  methods: {
    // 超出时调用的函数
    handleExceed(files, fileList) {
      this.$message.error('最多只能上传一张图片')
    },
    // 图片上传中调用的函数
    handleProgress(event, files, fileList) {
      this.$message.warning('文件上传中...')
    },
    // 文件上传失败
    handleError(err, file, fileList) {
      this.$message.error('文件上传失败')
    },
    // 文件上传成功调用的函数
    handleSuccess(response, file, fileList) {
      this.step = 1;
      console.log(response)
      if (response.data['sign'] === 'left') {
        this.form.leftFilename = response.data['filename']
        this.leftBase64 = 'data:image/png;base64,' + response.data['64Url']
      } else {
        this.form.rightFilename = response.data['filename']
        this.rightBase64 = 'data:image/png;base64,' + response.data['64Url']
      }

      let formData = new FormData()
      formData.append('file', file.raw)
      axios.post('/llava/uploadImage',formData);

      this.$message.success('文件上传成功啦')
    },
    // 点击开始识别按钮
    startDiagnosis() {
      // 卫语句
      if (this.form.leftFilename === '' || this.form.rightFilename === '') {
        this.$message.error('请先上传图片')
        return;
      }

      // 做一个过度
      let loadingText = 'LLAVA正在生成图片描述...'
      // 0.开启整页加载
      this.loading = this.$loading({
        lock: true,
        text: loadingText,
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      axios.post('/llava/getImageDescription', this.form).then(res => {

        this.form.description = res.data.data

        // 修改加载文本
        loadingText = '亮度增强网络正在努力工作...'
        this.loading.setText(loadingText)

        // 1.进行图片增强 并返回结果
        enhanceImage(this.form).then(res => {

          // 修改加载文本
          loadingText = '多模态网络正在努力预测...'
          this.loading.setText(loadingText)

          // 3.多模态模型获得疾病概率，并返回结果
          getProbList(this.form).then(finalResult => {
            // 反馈
            this.$message.success('模型诊断成功')

            // 关闭全局加载
            this.loading.close()

            // 设定的阈值
            let threshold = 0.8
            this.probData = []
            for (let i = 0; i < finalResult.data.length; i++) {
              if (finalResult.data[i].prob > threshold) {
                // 大于阈值 预测结果为1 同时获取中文识别结果，用于寻问大模型
                this.probData.push(1)
              } else {
                this.probData.push(0)
              }
            }
            this.drawResultEcharts()
            this.$refs.leftUpload.clearFiles()
            this.$refs.rightUpload.clearFiles()
            // 重置表单
            this.form = {
              leftFilename: '',
              rightFilename: '',
              leftDescription: '',
              rightDescription: '',
            }
          })
        })
      })
    },
    // 绘制结果柱状图
    drawResultEcharts() {
      let resultEcharts = echarts.init(document.querySelector('.result-area'));
      document.getElementById("result-area")?.removeAttribute("_echarts_instance_");
      resultEcharts.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: { // 坐标轴指示器，坐标轴触发有效
            type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        grid: {
          top: '10%',
          left: '2%',
          right: '2%',
          bottom: '0',
          containLabel: true
        },
        xAxis: [{
          type: 'category',
          data: this.diseaseBarDataX,
          axisTick: {
            alignWithLabel: true
          },
          axisLabel: {
            interval: 0,
            rotate: 40
          },
          splitLine: {
            show: false
          }
        }],
        yAxis: [{
          type: 'value',
          axisTick: {
            show: false
          },
          axisLabel: {
            show: false, // 不显示坐标轴上的文字
          },
          splitLine: {
            show: false // 隐藏y轴的背景线条
          }
        }],
        series: [{
          name: '是否患病（值为1及患病）',
          type: 'bar',
          stack: 'vistors',
          label: {
            show: true, //开启显示
            position: 'top', //在上方显示
            formatter: function (params) {
              // params.value 是当前柱状图的数据值
              return params.value === 1 ? '确诊' : '未确诊';
            },
            textStyle: { //数值样式
              color: 'color',//字体颜色
              fontSize: 14//字体大小
            }
          },
          barWidth: '60%',
          data: this.probData,
          //给柱状图整体设置颜色
          itemStyle: {
            normal: {
              color: '#4ad2ff'
            },
          },
          animationDuration
        }]
      })
    },
  },
  mounted() {
    this.$nextTick(function () {
      this.drawResultEcharts()
    })
  }
}
</script>

<style lang="less" scoped>
.container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;

  .upper-area {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 50%;

    .upload-area {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;

      .upload-file {
        width: 30%;
        height: 90%;
        display: flex;
        align-items: center;
        flex-direction: column;

        .img-preview {
          width: 100%;
          position: relative;
          margin-top: 15px;
          flex: 1;

          .inner-image-box {
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            padding-top: 10px;
            padding-bottom: 10px;
          }

          .image-background {
            position: absolute;
            width: 100%;
            height: 100%;
            z-index: -1;
            left: 0;
          }
        }
      }

      .middle-blank {
        width: 20%;
      }
    }

    .start-btn {
      margin-top: 45px;
      display: flex;
      align-items: center;
      background-color: rgba(115, 170, 229, 0.5);
      border-color: rgba(115, 170, 229, 0.5);
      color: #fff;
    }
  }

  .result-area {
    width: 100%;
    flex: 1;
  }
}
</style>